package log

import (
	"bytes"
	"fmt"
	"log"
	"runtime/debug"

	"gitee.com/worklz/dtm-tcc-demo/common/util"
	"github.com/sirupsen/logrus"
)

var Logger *logrus.Logger

// Info 记录信息日志
func Info(message string, withFields ...map[string]any) {
	if Logger == nil {
		message := fmt.Sprintf("[INFO] %s", message)
		if len(withFields) > 0 {
			withFieldsJson, _ := util.ToJson(withFields[0])
			message += " " + withFieldsJson
		}
		log.Println(message)
		return
	}
	if len(withFields) > 0 {
		Logger.WithFields(withFields[0]).Info(message)
		return
	}
	Logger.Info(message)
}

// Error 记录错误日志
func Error(message string, err any, withFields ...map[string]any) {
	if Logger == nil {
		message := fmt.Sprintf("[ERROR] %s", message)
		if len(withFields) > 0 {
			withFieldsJson, _ := util.ToJson(withFields[0])
			message += " " + withFieldsJson
		}
		log.Println(message)
		return
	}
	if err != nil {
		if errVal, ok := err.(error); ok {
			message += "\r\n" + ErrorStack(errVal)
		} else {
			if errStr, ok := err.(string); ok && errStr != "" {
				message += "\r\n" + errStr
			} else {
				message += "\r\n" + fmt.Sprintf("%v", err)
			}
		}
	}
	if len(withFields) > 0 {
		Logger.WithFields(withFields[0]).Error(message)
		return
	}
	Logger.Error(message)
}

// 获取错误堆栈信息
func ErrorStack(err error) string {
	if err == nil {
		return ""
	}
	var buf bytes.Buffer
	buf.WriteString(err.Error() + "\r\nStack:")

	// 按行处理堆栈信息
	stack := debug.Stack()
	row := 1
	for i, line := range bytes.Split(stack, []byte{'\n'}) {
		if i <= 4 {
			continue
		}
		buf.WriteString("\r\n")
		buf.Write(line)
		// buf.WriteByte('\n')

		// if i == 0 {
		// 	// 第一行通常是 goroutine 信息
		// 	buf.WriteString(string(line))
		// 	buf.WriteByte('\n')
		// } else if len(line) > 0 {
		// 	// 为非空行添加缩进
		// 	buf.WriteString("  ")
		// 	buf.Write(line)
		// 	buf.WriteByte('\n')
		// }
		row++
	}

	return buf.String()

}
